package controllers;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import openIDService.Authentication;
import openIDService.OpenIDService;
import openIDService.VerifyUser;

import org.openid4java.association.AssociationException;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.discovery.DiscoveryException;
import org.openid4java.message.MessageException;

import utilities.GestoreLink;

/**
 * Controller per il login
 * 
 */
@WebServlet("/login")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Se l'utente ha inserito le credenziali, le controlla e carica la pagina
	 * principale del forum. Altrimenti mostra nuovamente la pagina di login.
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		VerifyUser user = new VerifyUser(request);

		if (user.isAuthorized()) {
			response.sendRedirect(GestoreLink.getGestore().getElement("forum"));
		} else {
			request.getRequestDispatcher(
					GestoreLink.getGestore().getElement("Login")).forward(
					request, response);
		}
	}

	/**
	 * Se e' settato il parametro "userid" nella richiesta POST, avvia
	 * l'autenticazione.
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userid = request.getParameter("userid");
		if (userid != null) {

			OpenIDService service = new Authentication(response);

			try {
				service.execute(request, userid);

			} catch (DiscoveryException e) {
				error(request, response);
				e.printStackTrace();
			} catch (MessageException e) {
				error(request, response);
				e.printStackTrace();
			} catch (ConsumerException e) {
				error(request, response);
				e.printStackTrace();
			} catch (AssociationException e) {
				error(request, response);
				e.printStackTrace();
			}
		}

	}

	private static void error(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(
				GestoreLink.getGestore().getElement("LoginError")).forward(
				request, response);
	}

}